package com.zbkj.crmeb.merchant.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.agent.service.AgentService;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.*;
import com.zbkj.crmeb.export.vo.StoreOrderExcelVo;
import com.zbkj.crmeb.marketing.dao.StoreCouponDao;
import com.zbkj.crmeb.marketing.model.StoreCoupon;
import com.zbkj.crmeb.marketing.model.StoreCouponUser;
import com.zbkj.crmeb.marketing.request.StoreCouponSearchRequest;
import com.zbkj.crmeb.marketing.service.StoreCouponUserService;
import com.zbkj.crmeb.merchant.admin.service.MerAgentStoreOrderService;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.response.*;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.store.utilService.OrderUtils;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;
import com.zbkj.crmeb.system.model.SystemAdmin;
import com.zbkj.crmeb.system.response.StoreOrderItemResponse;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.model.UserTag;
import com.zbkj.crmeb.user.service.UserService;
import com.zbkj.crmeb.user.service.UserTagService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 服务商-订单管理 服务实现类
 *
 * @author lvmd
 * @date 2022-02-22
 */
@Slf4j
@Service
public class MerAgentStoreOrderServiceImp extends ServiceImpl<StoreOrderDao, StoreOrder> implements MerAgentStoreOrderService {

    @Resource
    private StoreOrderDao dao;
    @Resource
    private StoreCouponDao storeCouponDao;

    @Autowired
    private PriceUtil priceUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserTagService userTagService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    private PurchaseGoodsService purchaseGoodsService;
    @Autowired
    private StoreAccountInfoService storeAccountInfoService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    StoreCouponUserService storeCouponUserService;
    @Autowired
    StoreOrderService storeOrderService;
    @Autowired
    StoreOrderInfoService storeOrderInfoService;
    @Autowired
    StoreOrderStatusService storeOrderStatusService;
    @Autowired
    AgentService agentService;
    @Autowired
    private OrderUtils orderUtils;

    /**
     * 订单列表
     *
     * @param request
     * @param pageParamRequest
     * @return
     */
    @Override
    public StoreOrderAgentResponse listStoreOrders(StoreOrderSearchRequest request, PageParamRequest pageParamRequest) {
        SystemAdmin systemAdmin = systemAdminService.getInfo();
        boolean agentFlag = IdentityTypeEnum.AGENCY_ONE.getCode().equals(systemAdmin.getIdentityType());
        StoreOrderAgentResponse storeOrderResponse = new StoreOrderAgentResponse();
        //列表数据
        List<StoreOrderItemResponse> storeOrderItemResponseArrayList = new ArrayList<>();
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request, searchRequest);
        getStoreOrderListRequest(searchRequest);
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //查询子订单
        List<StoreOrderInfo> childOrderList = dao.selectChildOrderListByUnionQuery(searchRequest);
        if (childOrderList != null && childOrderList.size() > 0) {
            storeOrderItemResponseArrayList = formatChildOrder(childOrderList);
        }
        CommonPage<StoreOrderItemResponse> storeOrderItemResponseCommonPage = CommonPage.restPage(CommonPage.copyPageInfo(page, storeOrderItemResponseArrayList));
        storeOrderResponse.setList(storeOrderItemResponseCommonPage);
        //状态数量
        List<StoreOrderInfo> countList = getCount(request);
        //全部
        List<Integer> all = Stream.of(-2, -1, 0, 1, 2, 4, 5, 6).collect(Collectors.toList());
        Integer count = countList.stream().filter(e -> all.contains(e.getStatus())).map(StoreOrderInfo::getId).reduce(Integer::sum).orElse(0);
        //分组
        Map<Integer, Integer> countMap = countList.stream().filter(e -> e.getStatus() != null).collect(Collectors.toMap(StoreOrderInfo::getStatus, StoreOrderInfo::getId));
        storeOrderResponse.setStatus(
                new StoreOrderCountItemResponse(
                        count, //全部
                        getCountByStatus(countMap,OrderStatusEnum.UNPAID.getCode()), //未支付
                        getCountByStatus(countMap,OrderStatusEnum.NOT_SHIPPED.getCode()), //未发货
                        getCountByStatus(countMap,OrderStatusEnum.SHIPPED.getCode()), //待收货
                        getCountByStatus(countMap,OrderStatusEnum.COMPLETE.getCode()),//交易完成
                        getCountByStatus(countMap,OrderStatusEnum.APPLY_REFUND.getCode()),//退款中
                        getCountByStatus(countMap,OrderStatusEnum.REJECTED_SUCCESS.getCode()),//退货退款
                        getRefundedPartCount(request),//补偿性退款
                        getCountByStatus(countMap,OrderStatusEnum.CONFIRM.getCode()),//待确认
                        getCountByStatus(countMap,OrderStatusEnum.CANCEL.getCode())//已取消
                )
        );
        //头部数据
        pageParamRequest.setLimit(1);
        List<StoreOrderInfo> amountList = dao.getSumAllPriceByCondition(searchRequest);
        Map<String, StoreOrderInfo> amountMap = amountList.stream().collect(Collectors.toMap(StoreOrderInfo::getVerifyCode, e -> e));
        BigDecimal payPrice = amountList.stream().map(StoreOrderInfo::getPayPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal deductionPrice = amountList.stream().map(StoreOrderInfo::getDeductionPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        storeOrderResponse.setTop(
                new StoreOrderAgentTopItemResponse(
                        orderUtils.getCurrentCount(request.getStatus(), storeOrderResponse.getStatus()),
                        payPrice.add(deductionPrice),
                        agentFlag ? BigDecimal.ZERO : getPayPriceByType(amountMap,Constants.PAY_TYPE_WE_CHAT),
                        agentFlag ? BigDecimal.ZERO : getPayPriceByType(amountMap, Constants.PAY_TYPE_YUE),
                        getProfitAmount(request),
                        payPrice
                )
        );
        return storeOrderResponse;
    }

    private BigDecimal getPayPriceByType(Map<String, StoreOrderInfo> amoutMap,String payType) {
        BigDecimal price = BigDecimal.ZERO;
        StoreOrderInfo storeOrderInfo = amoutMap.get(payType);
        if(storeOrderInfo != null){
            price = storeOrderInfo.getPayPrice();
        }
        return price;
    }

    private int getRefundedPartCount(StoreOrderSearchRequest request) {
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request,searchRequest);
        searchRequest.setStatus(Constants.ORDER_STATUS_REFUNDED_PART);
        getStoreOrderListRequest(searchRequest);
        return dao.getRefundedPartCount(searchRequest);
    }

    private int getCountByStatus(Map<Integer, Integer> countMap,Integer status) {
        Integer count = countMap.get(status);
        return count == null ? 0 : count;
    }

    private BigDecimal getProfitAmount(StoreOrderSearchRequest request) {
        SystemAdmin systemAdmin = systemAdminService.getInfo();
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request, searchRequest);
        getStoreOrderListRequest(searchRequest);
        if (IdentityTypeEnum.AGENCY_ONE.getCode().equals(systemAdmin.getIdentityType())) {
            return dao.getProfitAmount(searchRequest);
        } else if (IdentityTypeEnum.AGENCY_TWO.getCode().equals(systemAdmin.getIdentityType())) {
            return dao.getSecondProfitAmount(searchRequest);
        }
        return BigDecimal.ZERO;
    }

    private List<StoreOrderItemResponse> formatChildOrder(List<StoreOrderInfo> childOrderList) {
        SystemAdmin systemAdmin = systemAdminService.getInfo();
        Boolean profitFlag = null;
        if (IdentityTypeEnum.AGENCY_ONE.getCode().equals(systemAdmin.getIdentityType())) {
            profitFlag = true;
        } else {
            profitFlag = false;
        }
        //子订单根据order_id分组查询主订单信息
        Set<Integer> orderIdList = childOrderList.stream().map(StoreOrderInfo::getOrderId).collect(Collectors.toSet());
        List<StoreOrder> storeOrderList = dao.selectList(Wrappers.lambdaQuery(StoreOrder.class).in(StoreOrder::getId, orderIdList).orderByDesc(StoreOrder::getId));
        //下单用户列表
        Set<Integer> userIdList = storeOrderList.stream().map(StoreOrder::getUid).collect(Collectors.toSet());
        List<User> userList = userService.list(Wrappers.lambdaQuery(User.class).in(User::getUid, userIdList));
        //用户标签列表
        Map<Integer, List<UserTagInfo>> tagMap = new HashMap<>();
        //推广人列表
        Map<Integer, User> spreadMap = new HashMap<>();
        userList.forEach(e -> {
            if (spreadMap.get(e.getUid()) == null) {
                User spread = Optional.ofNullable(userService.getById(e.getSpreadUid())).orElse(new User());
                spreadMap.put(e.getUid(), spread);
            }
            List<UserTagInfo> userTagInfoList;
            if (StringUtils.isNotBlank(e.getTagIds()) && tagMap.get(e.getUid()) == null) {
                List<Integer> tagIdList = Stream.of(e.getTagIds().split(",")).map(Integer::parseInt).collect(Collectors.toList());
                List<UserTag> UserTagList = userTagService.list(Wrappers.lambdaQuery(UserTag.class).in(UserTag::getId, tagIdList));
                userTagInfoList = UserTagList.stream().map(tag -> new UserTagInfo().setTagId(tag.getId()).setTagName(tag.getName())).collect(Collectors.toList());
                tagMap.put(e.getUid(), userTagInfoList);
            }
        });

        Map<Integer, List<StoreOrderInfo>> infoMap = childOrderList.stream().collect(Collectors.groupingBy(StoreOrderInfo::getOrderId));
        //商品信息
        List<Integer> productIdList = childOrderList.stream().map(StoreOrderInfo::getProductId).distinct().collect(Collectors.toList());
        List<StoreProduct> productList = storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, productIdList)
                .select(StoreProduct::getId,StoreProduct::getSuppliersId,StoreProduct::getSuppliersName));
        Map<Integer, StoreProduct> productMap = productList.stream().collect(Collectors.toMap(StoreProduct::getId, e -> e));
        //订单物流
        List<Integer> orderInfoIdList = childOrderList.stream().map(StoreOrderInfo::getId).distinct().collect(Collectors.toList());
        List<OrderInfoDelivery> deliveryList = orderInfoDeliveryService.list(Wrappers.<OrderInfoDelivery>lambdaQuery().in(OrderInfoDelivery::getOrderInfoId, orderInfoIdList)
                .groupBy(OrderInfoDelivery::getOrderInfoId).orderByDesc(OrderInfoDelivery::getCreateTime));
        Map<Integer, OrderInfoDelivery> deliveryMap = deliveryList.stream().collect(Collectors.toMap(OrderInfoDelivery::getOrderInfoId, e -> e));
        //备注
        List<String> childOrderNoList = childOrderList.stream().map(StoreOrderInfo::getChildOrderNumber).distinct().collect(Collectors.toList());
        Map<String, String> noteMap = storeOrderStatusService.getNoteMap(childOrderNoList,Constants.ORDER_PLATFORM_NOTE);
        //采购单信息
        Map<Integer, List<PurchaseGoods>> purchaseGoodsMap = new HashMap<>();
        List<Integer> filterOrderInfoIdList = childOrderList.stream().filter(e -> !Objects.equals(e.getIsEurope(), ProductTypeEnum.INSIDE.getCode()) && !Objects.equals(e.getAutonomous(), 1)).map(StoreOrderInfo::getId).distinct().collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(filterOrderInfoIdList)){
            List<PurchaseGoods> purchaseList = purchaseGoodsService.list(Wrappers.lambdaQuery(PurchaseGoods.class).eq(PurchaseGoods::getPushStatus,1).eq(PurchaseGoods::getPushType, 0)
                    .in(PurchaseGoods::getStoreOrderInfoId, filterOrderInfoIdList));
            purchaseGoodsMap = purchaseList.stream().collect(Collectors.groupingBy(PurchaseGoods::getStoreOrderInfoId));
        }

        List<StoreOrderItemResponse> storeOrderItemResponseArrayList = new ArrayList<>();
        for (StoreOrder storeOrder : storeOrderList) {
            StoreOrderItemResponse storeOrderItemResponse = new StoreOrderItemResponse();
            BeanUtils.copyProperties(storeOrder, storeOrderItemResponse);
            ChannelMerchant channelMerchant = channelMerchantService.getById(storeOrder.getMerId());
            if (null != channelMerchant) {
                storeOrderItemResponse.setChannelName(channelMerchant.getChannelName());
            }
            //配送方式
            storeOrderItemResponse.setShippingType(storeOrder.getShippingType());
            //使用积分
            storeOrderItemResponse.setUseIntegral(new BigDecimal(storeOrder.getUseIntegral()));
            //支付方式
            storeOrderItemResponse.setPayTypeStr(getPayType(storeOrder.getPayType()));
            //下单用户
            storeOrderItemResponse.setOrderCreateName(storeOrder.getCreateName());
            storeOrderItemResponse.setUserTagInfoList(tagMap.get(storeOrder.getUid()));
            if (spreadMap.get(storeOrder.getUid()) != null) {
                storeOrderItemResponse.getSpreadInfo().setId(spreadMap.get(storeOrder.getUid()).getUid());
                storeOrderItemResponse.getSpreadInfo().setName(spreadMap.get(storeOrder.getUid()).getNickname());
            }
            //子订单处理信息
            List<OrderInfoProductResponse> childOrderInfoList = new ArrayList<>();
            List<StoreOrderInfo> orderInfoList = infoMap.get(storeOrder.getId());
            for (StoreOrderInfo storeOrderInfo : orderInfoList) {
                StoreProduct product = productMap.get(storeOrderInfo.getProductId());
                //解析商品详情JSON
                StoreOrderInfoVo infoVo = new StoreOrderInfoVo();
                BeanUtils.copyProperties(storeOrderInfo, infoVo, "info");
                infoVo.setInfo(JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class));
                OrderInfoProductResponse orderInfoProductResponse = new OrderInfoProductResponse();
                if(null != product){
                    infoVo.getInfo().getProductInfo().setSupplierName(product.getSuppliersName());
                    orderInfoProductResponse.setSuppliersId(product.getSuppliersId());
                    orderInfoProductResponse.setSuppliersName(product.getSuppliersName());
                }
                StoreProductAttrValue attrInfo = infoVo.getInfo().getProductInfo().getAttrInfo();
                orderInfoProductResponse.setSkuId(attrInfo.getSourceSkuId());
                orderInfoProductResponse.setBarCode(attrInfo.getBarCode());
                orderInfoProductResponse.setCost(attrInfo.getCost());
                orderInfoProductResponse.setSourceCost(attrInfo.getSourceCost());
                orderInfoProductResponse.setOtPrice(infoVo.getInfo().getProductInfo().getAttrInfo().getOtPrice());
                orderInfoProductResponse.setOrderInfoId(infoVo.getId());
                orderInfoProductResponse.setProductId(infoVo.getProductId());
                orderInfoProductResponse.setCartNum(infoVo.getInfo().getCartNum());
                orderInfoProductResponse.setImage(attrInfo.getImage());
                orderInfoProductResponse.setStoreName(infoVo.getInfo().getProductInfo().getStoreName());
                orderInfoProductResponse.setChildOrderNumber(infoVo.getChildOrderNumber());
                orderInfoProductResponse.setStatus(infoVo.getStatus());
                orderInfoProductResponse.setProductPaidPrice(attrInfo.getProductPaidPrice());
                orderInfoProductResponse.setPaidPrice(attrInfo.getPaidPrice());
                orderInfoProductResponse.setDeductionPrice(attrInfo.getDeductionPrice());
                orderInfoProductResponse.setUseIntegral(attrInfo.getUseIntegral());
                BigDecimal subTotalPrice = attrInfo.getSubTotalPrice() == null ? attrInfo.getPrice().add(attrInfo.getTaxPrice() == null ? BigDecimal.ZERO : attrInfo.getTaxPrice().add(attrInfo.getSecondPrice() == null ? BigDecimal.ZERO : attrInfo.getSecondPrice())) : attrInfo.getSubTotalPrice();
                orderInfoProductResponse.setSubTotalPrice(subTotalPrice);
                //橙子商品设置keyword为itemCode
                String keyword = infoVo.getInfo().getProductInfo().getKeyword();
                if (ProductTypeEnum.ORANGE.getCode().equals(infoVo.getInfo().getProductInfo().getIsEurope())) {
                    StoreProductAttrResult result = storeProductAttrResultService.getByProductId(infoVo.getInfo().getProductId());
                    JSONArray jsonArray = JSONArray.parseArray(result.getResult());
                    for (Object o : jsonArray) {
                        JSONObject jsonObject = JSONObject.parseObject(o.toString());
                        if (Objects.equals(jsonObject.get("sourceSkuId"), infoVo.getInfo().getProductInfo().getAttrInfo().getSourceSkuId())) {
                            keyword = (String) jsonObject.get("skuCode");
                        }
                    }
                }
                orderInfoProductResponse.setKeyword(keyword);
                orderInfoProductResponse.setSuk(infoVo.getInfo().getProductInfo().getAttrInfo().getSuk());
                orderInfoProductResponse.setTempName(StockAreaTempEnum.getByTempId(infoVo.getInfo().getProductInfo().getTempId()).getStockAreaName());
                orderInfoProductResponse.setPrice(infoVo.getInfo().getProductInfo().getAttrInfo().getPrice());
                orderInfoProductResponse.setTotalPrice(infoVo.getInfo().getProductInfo().getAttrInfo().getPrice().multiply(new BigDecimal(infoVo.getInfo().getCartNum())));
                OrderInfoDelivery delivery = deliveryMap.get(infoVo.getId());
                orderInfoProductResponse.setDelivery(delivery);
                if(Objects.equals(storeOrderInfo.getIsEurope(),ProductTypeEnum.INSIDE.getCode())){
                    orderInfoProductResponse.setProcureStatus(ProcureStatusEnum.NO_PROCURE.getType());
                } else if(Objects.equals(storeOrderInfo.getAutonomous(),1)){
                    orderInfoProductResponse.setProcureStatus(ProcureStatusEnum.AUTO_PROCURE.getType());
                } else {
                    List<PurchaseGoods> purchaseGoodsList = purchaseGoodsMap.get(infoVo.getId());
                    orderInfoProductResponse.setProcureStatus((CollectionUtils.isEmpty(purchaseGoodsList) && delivery == null) ? ProcureStatusEnum.FOR_PROCURE.getType() : ProcureStatusEnum.PROCURE.getType());
                    if(CollectionUtils.isNotEmpty(purchaseGoodsList)){
                        orderInfoProductResponse.setDeliveryOrderNoList(purchaseGoodsList.stream().map(PurchaseGoods::getChannelOrderSn).collect(Collectors.toList()));
                    }
                }
                orderInfoProductResponse.setDelivery(delivery);
                orderInfoProductResponse.setOrderCode(Integer.toString(Integer.parseInt(infoVo.getOrderId() + "" + infoVo.getId()), 36).toUpperCase());
                orderInfoProductResponse.setDeliveryAddress(infoVo.getDeliveryAddress());
                orderInfoProductResponse.setFirstPrice(infoVo.getInfo().getProductInfo().getAttrInfo().getFirstPrice());
                orderInfoProductResponse.setSecondPrice(infoVo.getInfo().getProductInfo().getAttrInfo().getSecondPrice());
                orderInfoProductResponse.setTaxPrice(infoVo.getInfo().getProductInfo().getAttrInfo().getTaxPrice());
                orderInfoProductResponse.setBrandName(infoVo.getInfo().getProductInfo().getBrandName());
                orderInfoProductResponse.setRefundReasonTime(storeOrderInfo.getRefundReasonTime());
                orderInfoProductResponse.setRefundReasonWapImg(storeOrderInfo.getRefundReasonWapImg());
                orderInfoProductResponse.setRefundReasonWapExplain(storeOrderInfo.getRefundReasonWapExplain());
                orderInfoProductResponse.setRefundReasonWap(storeOrderInfo.getRefundReasonWap());
                orderInfoProductResponse.setRefundReason(storeOrderInfo.getRefundReason());
                orderInfoProductResponse.setFirstAgentProfit(storeOrderInfo.getFirstAgentProfit());
                orderInfoProductResponse.setSecondAgentProfit(storeOrderInfo.getSecondAgentProfit());
                StoreCartResponse storeCartResponse = JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class);
                // 服务商成本价、供货价
                if (profitFlag) {
                    orderInfoProductResponse.setAgentCostPrice(storeCartResponse.getProductInfo().getAttrInfo().getFirstAgentCost());
                    orderInfoProductResponse.setAgentSupplyPrice(storeCartResponse.getProductInfo().getAttrInfo().getSecondAgentCost());
                } else {
                    orderInfoProductResponse.setAgentCostPrice(storeCartResponse.getProductInfo().getAttrInfo().getSecondAgentCost());
                    orderInfoProductResponse.setAgentSupplyPrice(storeCartResponse.getProductInfo().getAttrInfo().getCost());
                }
                childOrderInfoList.add(orderInfoProductResponse);
            }
            storeOrderItemResponse.setChildOrderList(childOrderInfoList);
            // 处理总订单利润
            BigDecimal profit;
            if (profitFlag) {
                profit = childOrderInfoList.stream().map(OrderInfoProductResponse::getFirstAgentProfit).reduce(BigDecimal.ZERO, BigDecimal::add);
            } else {
                profit = childOrderInfoList.stream().map(OrderInfoProductResponse::getSecondAgentProfit).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            storeOrderItemResponse.setProfit(profit);
            storeOrderItemResponseArrayList.add(storeOrderItemResponse);
        }
        return storeOrderItemResponseArrayList;
    }

    private void getStoreOrderListRequest(StoreOrderSearchRequest request) {
        request.setMerIds(systemAdminService.getAdminAgentMerIds());
        // 暂时处理
        if (CollectionUtils.isEmpty(request.getMerIds())) {
            request.setMerIds(Collections.singletonList(-1));
        }

        if (StringUtils.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(request.getDateLimit());
            request.setStartTime(dateLimitUtilVo.getStartTime());
            request.setEndTime(dateLimitUtilVo.getEndTime());
        }
        String where = " 1=1";
        where += " and a.picking_id  = 0 ";
        if (request.getShippingType() != null) {
            where += " and a.shipping_type  = " + request.getShippingType();
        }
        if (request.getCouponId() != null) {
            where += " and a.coupon_id in (select id from eb_store_coupon_user where coupon_id = " + request.getCouponId() + " ) ";
        }

        String status = request.getStatus();
        if (null != status) {
            List<Integer> orderStatusList = new ArrayList<>();
            Integer orderStatus = null; //订单状态
            Integer refundStatus = null; //退款状态
            switch (status) {
                case Constants.ORDER_STATUS_ALL:
                    orderStatusList = Stream.of(0, 1, 2, 4, 5, 6, -1, -2).collect(Collectors.toList());
                    break;
                case Constants.ORDER_STATUS_UNPAID: //未支付
                    orderStatus = 0;
                    break;
                case Constants.ORDER_STATUS_NOT_SHIPPED: //未发货
                    orderStatus = 1;
                    break;
                case Constants.ORDER_STATUS_SPIKE: //待收货
                    orderStatus = 2;
                    break;
                case Constants.ORDER_STATUS_BARGAIN: //待评价
                    orderStatus = 3;
                    break;
                case Constants.ORDER_STATUS_COMPLETE: //交易完成
                    orderStatus = 4;
                    break;
                case Constants.ORDER_STATUS_CANCEL: //取消
                    orderStatus = 5;
                    break;
                case Constants.ORDER_STATUS_REFUNDING: //退款中
                    orderStatus = -1;
                    break;
                case Constants.ORDER_STATUS_REFUNDED: //退货退款
                    orderStatus = -2;
                    break;
                case Constants.ORDER_STATUS_REFUNDED_PART: //补偿性退款
                    refundStatus = 3;
                    break;
                case Constants.ORDER_STATUS_CONFIRM: //待确认
                    orderStatus = OrderStatusEnum.CONFIRM.getCode();
                    break;
                default:
                    //其他传状态不存在的-99
                    orderStatus = -99;
                    break;
            }
            if (CollectionUtils.isNotEmpty(orderStatusList)) {
                where += " and b.status in " + orderStatusList.toString().replace("[", "(").replace("]", ")");
            }

            if (orderStatus != null) {
                where += " and b.status  = " + orderStatus;
            }

            if (refundStatus != null) {
                where += " and b.refund_status  = " + refundStatus;
            }

        }
        request.setWhere(where);
        request.setIsIntegral(request.getIsIntegral());

    }


    /**
     * 获取总数
     *
     * @param request 请求参数
     * @return Integer
     * @author Mr.Zhang
     * @since 2020-06-12
     */
    private List<StoreOrderInfo> getCount(StoreOrderSearchRequest request) {
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request, searchRequest);
        searchRequest.setStatus(null);
        getStoreOrderListRequest(searchRequest);
        return dao.selectChildCountByCondition(searchRequest);
    }

    /**
     * h5 订单查询 where status 封装
     * 退款状态（0 未退款 1 申请中 2 已退款）
     * 订单状态（-1 : 申请退款 -2 : 退货成功 0：未支付，待发货；1：待收货；2：已收货，待评价；3：已完成；4：已取消；）
     *
     * @param queryWrapper 查询条件
     * @param status       状态
     */
    public void statusApiByWhere(LambdaQueryWrapper<StoreOrder> queryWrapper, int status) {
        switch (status) {
            case Constants.ORDER_STATUS_H5_UNPAID: // 未支付
                queryWrapper.eq(StoreOrder::getPaid, false);
                queryWrapper.eq(StoreOrder::getStatus, 0);
                queryWrapper.eq(StoreOrder::getRefundStatus, 0);
                break;
            case Constants.ORDER_STATUS_H5_NOT_SHIPPED: // 待发货
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getStatus, 1);
                //queryWrapper.eq(StoreOrder::getRefundStatus, 0);
                break;
            case Constants.ORDER_STATUS_H5_SPIKE: // 待收货
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getStatus, 2);
                //queryWrapper.eq(StoreOrder::getRefundStatus, 0);
                break;
            case Constants.ORDER_STATUS_H5_BARGAIN: //  待评价
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getStatus, 3);
                //queryWrapper.eq(StoreOrder::getRefundStatus, 0);
                break;
            case Constants.ORDER_STATUS_H5_COMPLETE: // 已完成
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getStatus, 4);
                //queryWrapper.eq(StoreOrder::getRefundStatus, 0);
                break;
            case Constants.ORDER_STATUS_H5_CANCEL: // 已取消
                queryWrapper.eq(StoreOrder::getPaid, false);
                queryWrapper.eq(StoreOrder::getStatus, 5);
                //queryWrapper.eq(StoreOrder::getRefundStatus, 0);
                break;
            case Constants.ORDER_STATUS_H5_REFUNDING: // 退款中
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getRefundStatus, 1);
                break;
            case Constants.ORDER_STATUS_H5_REFUNDED: // 已退款
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getRefundStatus, 2);//退货退款
                break;
            case Constants.ORDER_STATUS_H5_REFUND: // 退款
                queryWrapper.eq(StoreOrder::getPaid, true);
                queryWrapper.eq(StoreOrder::getRefundStatus, 3); //补偿性退款
                break;
        }
        queryWrapper.eq(StoreOrder::getIsDel, false);
        queryWrapper.eq(StoreOrder::getIsSystemDel, false);
    }


    /**
     * 获取支付文字
     *
     * @param payType String 支付方式
     * @author Mr.Zhang
     * @since 2020-06-12
     */
    private String getPayType(String payType) {
        switch (payType) {
            case Constants.PAY_TYPE_WE_CHAT:
                return Constants.PAY_TYPE_STR_WE_CHAT;
            case Constants.PAY_TYPE_WE_CHAT_NATIVE:
            	return Constants.PAY_TYPE_STR_WE_CHAT_NATIVE;
            case Constants.PAY_TYPE_YUE:
                return Constants.PAY_TYPE_STR_YUE;
            case Constants.PAY_TYPE_OFFLINE:
                return Constants.PAY_TYPE_STR_OFFLINE;
            case Constants.PAY_TYPE_ALI_PAY:
                return Constants.PAY_TYPE_STR_ALI_PAY;
            case Constants.PAY_TYPE_TMALL_PAY:
                return Constants.PAY_TYPE_STR_TMALL_PAY;
            case Constants.PAY_TYPE_HK_PAY:
                return Constants.PAY_TYPE_STR_HK_PAY;
            case Constants.PAY_TYPE_ORAGE_PAY:
                return Constants.PAY_TYPE_STR_ORAGE_PAY;
            case Constants.PAY_TYPE_ADAPAY_DEGREE:
            	return Constants.PAY_TYPE_STR_ADAPAY_DEGREE;
            case Constants.PAY_TYPE_ADAPAY_CN:
            	return Constants.PAY_TYPE_STR_ADAPAY_CN;
            default:
                return Constants.PAY_TYPE_STR_OTHER;
        }
    }


    private String getRefundStatusStr(Integer refundStatus) {
        if (null == refundStatus) {
            return "";
        }
        if (Integer.valueOf(0).equals(refundStatus)) {
            return "未退款";
        } else if (Integer.valueOf(1).equals(refundStatus)) {
            return "申请中";
        } else if (Integer.valueOf(2).equals(refundStatus)) {
            return "已退款";
        } else if (Integer.valueOf(3).equals(refundStatus)) {
            return "补偿性退款";
        }
        return "";
    }


    private String getStatusStr(Integer status) {
        if (status == null) {
            return "";
        }
        OrderStatusEnum[] orderStatusEnums = OrderStatusEnum.values();
        for (OrderStatusEnum orderStatusEnum : orderStatusEnums) {
            if (orderStatusEnum.getCode().equals(status)) {
                return orderStatusEnum.getMsg();
            }
        }
        return "";
    }

    /**
     * 优惠券下拉列表
     *
     * @param request
     * @return
     */
    @Override
    public List<StoreCoupon> listCoupons(StoreCouponSearchRequest request) {
        List<Integer> merIdList = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIdList)) {
            return new ArrayList<>();
        }

        LambdaQueryWrapper<StoreCoupon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(StoreCoupon::getId, StoreCoupon::getName);
        lambdaQueryWrapper.eq(StoreCoupon::getIsDel, false);
        lambdaQueryWrapper.in(StoreCoupon::getMerId, merIdList);
        lambdaQueryWrapper.orderByDesc(StoreCoupon::getCreateTime);

        return storeCouponDao.selectList(lambdaQueryWrapper);
    }

    /**
     * 订单导出
     *
     * @param request
     * @param pageParamRequest
     * @return
     */
    @Override
    public List<StoreOrderExcelVo> getExportList(StoreOrderSearchRequest request, PageParamRequest pageParamRequest) {
        getStoreOrderListRequest(request);
//        request.setRequestSource("ADMIN");
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
//        List<StoreOrderProduct> storeOrderList = dao.getExportList(request);
        List<StoreOrderInfo> childOrderList = dao.selectChildOrderListByUnionQuery(request);

        if (childOrderList != null && childOrderList.size() > 0) {
            List<StoreOrderExcelVo> list = formatStoreOrderExcelVoNew(childOrderList);
            return list;
        }
        return new ArrayList<StoreOrderExcelVo>();
    }

    @Override
    public StoreOrderInfoResponse info(Integer id) {
        //判断几级服务商
        Integer agentId = systemAdminService.getAdminAgentId();
        StoreOrder storeOrder = getById(id);
        if(null == storeOrder){
            throw new CrmebException("没有找到订单信息");
        }
        StoreOrderInfoResponse storeOrderInfoResponse = new StoreOrderInfoResponse();
        //判断商户是否直属服务商
        if(null != storeOrder.getMerId() && 0!= storeOrder.getMerId()){
            ChannelMerchant channelMerchant =  channelMerchantService.getById(storeOrder.getMerId());
            if(null!=channelMerchant){
                storeOrderInfoResponse.setMerPhone(channelMerchant.getContactPhone());
                storeOrderInfoResponse.setMerName(channelMerchant.getChannelName());
            }
        }
        BeanUtils.copyProperties(storeOrder, storeOrderInfoResponse);
        //优惠券名称
        StoreCouponUser storeCouponUser = Optional.ofNullable(storeCouponUserService.getById(storeOrder.getCouponId())).orElse(new StoreCouponUser());
        storeOrderInfoResponse.setCouponName(storeCouponUser.getName());
        storeOrderInfoResponse.setPayTypeStr(getPayType(storeOrder.getPayType()));
        storeOrderInfoResponse.setStatusStr(storeOrderService.getStatus(storeOrder));
        //下单用户
        storeOrderInfoResponse.setOrderCreateName(storeOrder.getCreateName());
        //用户信息
        User user = userService.getById(storeOrder.getUid());
        List<UserTagInfo> userTagInfoList = new ArrayList<>();
        if(StringUtils.isNotBlank(user.getTagIds())){
            List<Integer> tagIdList= Stream.of(user.getTagIds().split(",")).map(Integer::parseInt).collect(Collectors.toList());
            List<UserTag> UserTagList = userTagService.list(Wrappers.lambdaQuery(UserTag.class).in(UserTag::getId, tagIdList));
            userTagInfoList = UserTagList.stream().map(tag -> new UserTagInfo().setTagId(tag.getId()).setTagName(tag.getName())).collect(Collectors.toList());
        }
        storeOrderInfoResponse.setUserTagInfoList(userTagInfoList);
        User spread = userService.getById(user.getSpreadUid());
        if(spread!=null) {
            storeOrderInfoResponse.getSpreadInfo().setId(spread.getUid());
            storeOrderInfoResponse.getSpreadInfo().setName(spread.getNickname());
        }
        storeOrderInfoResponse.setUser(user);
        storeOrderInfoResponse.setUseIntegral(BigDecimal.valueOf(Optional.ofNullable(storeOrder.getUseIntegral()).orElse(0)));
        storeOrderInfoResponse.setGainIntegral(BigDecimal.valueOf(Optional.ofNullable(storeOrder.getGainIntegral()).orElse(0)));
        storeOrderInfoResponse.setBackIntegral(BigDecimal.valueOf(Optional.ofNullable(storeOrder.getBackIntegral()).orElse(0)));

        List<StoreOrderInfoVo> orderInfoVoList = storeOrderInfoService.getOrderListByOrderId(storeOrder.getId());
        List<OrderInfoProductResponse> productList = new ArrayList<>();
        for(StoreOrderInfoVo infoVo : orderInfoVoList){
            OrderInfoProductResponse orderInfoProductResponse = new OrderInfoProductResponse();
            StoreProduct storeProductPram = new StoreProduct();
            storeProductPram.setId(infoVo.getProductId());
            StoreProduct storeProductResponse = storeProductService.getByEntity(storeProductPram);
            if(null!=storeProductResponse){
                orderInfoProductResponse.setSuppliersId(storeProductResponse.getSuppliersId());
                orderInfoProductResponse.setSuppliersName(storeProductResponse.getSuppliersName());
                if(storeProductResponse.getIsEurope() == ProductTypeEnum.INSIDE.getCode()){
                    orderInfoProductResponse.setProcureStatus(ProcureStatusEnum.NO_PROCURE.getType());
                }
            }
            StoreProductCartProductInfoResponse productInfo = infoVo.getInfo().getProductInfo();
            StoreProductAttrValue attrInfo = productInfo.getAttrInfo();
//            orderInfoProductResponse.setCost(attrInfo.getCost());
//            orderInfoProductResponse.setSourceCost(attrInfo.getSourceCost());
            orderInfoProductResponse.setOtPrice(attrInfo.getOtPrice());
            orderInfoProductResponse.setOrderInfoId(infoVo.getId());
            orderInfoProductResponse.setProductId(infoVo.getProductId());
            orderInfoProductResponse.setCartNum(infoVo.getInfo().getCartNum());
            orderInfoProductResponse.setImage(attrInfo.getImage());
            orderInfoProductResponse.setStoreName(infoVo.getInfo().getProductInfo().getStoreName());
            orderInfoProductResponse.setChildOrderNumber(infoVo.getChildOrderNumber());
            orderInfoProductResponse.setStatus(infoVo.getStatus());
            orderInfoProductResponse.setProductPaidPrice(attrInfo.getProductPaidPrice());
            orderInfoProductResponse.setPaidPrice(attrInfo.getPaidPrice());
            orderInfoProductResponse.setDeductionPrice(attrInfo.getDeductionPrice());
            orderInfoProductResponse.setUseIntegral(attrInfo.getUseIntegral());
//            orderInfoProductResponse.setIsEurope(infoVo.getInfo().getProductInfo().getIsEurope());
            orderInfoProductResponse.setIsEurope(Objects.nonNull(infoVo.getIsEurope()) ? infoVo.getIsEurope() : infoVo.getInfo().getProductInfo().getIsEurope());
            BigDecimal subTotalPrice = attrInfo.getSubTotalPrice() == null ? attrInfo.getPrice().add(attrInfo.getTaxPrice()==null?BigDecimal.ZERO:attrInfo.getTaxPrice().add(attrInfo.getSecondPrice()==null?BigDecimal.ZERO:attrInfo.getSecondPrice())) : attrInfo.getSubTotalPrice();
            orderInfoProductResponse.setSubTotalPrice(subTotalPrice);
            if(attrInfo.getInitialPaidPrice() != null){
                orderInfoProductResponse.setChangePrice(attrInfo.getPaidPrice().subtract(attrInfo.getInitialPaidPrice()));
            }
            //橙子商品设置keyword为itemCode
            String keyword = infoVo.getInfo().getProductInfo().getKeyword();
            if(ProductTypeEnum.ORANGE.getCode().equals(infoVo.getInfo().getProductInfo().getIsEurope())){
                StoreProductAttrResult result = storeProductAttrResultService.getByProductId(infoVo.getInfo().getProductId());
                JSONArray jsonArray = JSONArray.parseArray(result.getResult());
                for (Object o : jsonArray) {
                    JSONObject jsonObject = JSONObject.parseObject(o.toString());
                    if(Objects.equals(jsonObject.get("sourceSkuId"),attrInfo.getSourceSkuId())){
                        keyword = (String) jsonObject.get("skuCode");
                    }
                }
            }
            orderInfoProductResponse.setKeyword(keyword);
            orderInfoProductResponse.setSuk(attrInfo.getSuk());
            orderInfoProductResponse.setTempId(infoVo.getInfo().getProductInfo().getTempId());
            orderInfoProductResponse.setTempName(StockAreaTempEnum.getByTempId(infoVo.getInfo().getProductInfo().getTempId()).getStockAreaName());
            //一级服务商
            if(Objects.equals(attrInfo.getFirstAgentId(),agentId)){
                orderInfoProductResponse.setAgentCostPrice(attrInfo.getFirstAgentCost());
                orderInfoProductResponse.setAgentSupplyPrice(Objects.isNull(attrInfo.getSecondAgentId()) ? attrInfo.getCost() : attrInfo.getSecondAgentCost());
            }
            //二级
            if(Objects.equals(attrInfo.getSecondAgentId(),agentId)){
                orderInfoProductResponse.setAgentCostPrice(attrInfo.getSecondAgentCost());
                orderInfoProductResponse.setAgentSupplyPrice(attrInfo.getCost());
            }
            orderInfoProductResponse.setPrice(attrInfo.getPrice());
            orderInfoProductResponse.setTotalPrice(attrInfo.getPrice().multiply(new BigDecimal(infoVo.getInfo().getCartNum())));
            OrderInfoDelivery delivery = orderInfoDeliveryService.selectDeliveryByOrderInfoId(infoVo.getId());
            orderInfoProductResponse.setDelivery(delivery);
            orderInfoProductResponse.setUserDelivery(orderInfoDeliveryService.getOne(Wrappers.<OrderInfoDelivery>lambdaQuery()
                    .eq(OrderInfoDelivery::getOrderInfoId,infoVo.getId()).eq(OrderInfoDelivery::getChannel,5).orderByDesc(OrderInfoDelivery::getId).last("LIMIT 1")));
            if(null == orderInfoProductResponse.getProcureStatus() || orderInfoProductResponse.getProcureStatus()!= ProcureStatusEnum.NO_PROCURE.getType()){
                List<PurchaseGoods> purchaseGoodsList = purchaseGoodsService.list(Wrappers.lambdaQuery(PurchaseGoods.class).eq(PurchaseGoods::getPushType, 0).eq(PurchaseGoods::getStoreOrderInfoId, infoVo.getId()));
                List<String> deliveryOrderNoList = new ArrayList<>();
                if(CollectionUtils.isNotEmpty(purchaseGoodsList)){
                    purchaseGoodsList.forEach(goods->{
                        if(Objects.equals(goods.getPushStatus(),"1")){
                            orderInfoProductResponse.setProcureStatus(ProcureStatusEnum.PROCURE.getType());
                            deliveryOrderNoList.add(goods.getChannelOrderSn());
                        }
                    });
                }
                orderInfoProductResponse.setDeliveryOrderNoList(deliveryOrderNoList);
                if(null == orderInfoProductResponse.getProcureStatus()){
                    orderInfoProductResponse.setProcureStatus(ProcureStatusEnum.FOR_PROCURE.getType());
                }
            }
            orderInfoProductResponse.setOrderCode(Integer.toString(Integer.parseInt(infoVo.getOrderId() + "" + infoVo.getId()), 36).toUpperCase());
            orderInfoProductResponse.setDeliveryAddress(infoVo.getDeliveryAddress());
            orderInfoProductResponse.setSecondPrice(attrInfo.getSecondPrice());
            orderInfoProductResponse.setTaxPrice(attrInfo.getTaxPrice());
            orderInfoProductResponse.setBrandName(infoVo.getInfo().getProductInfo().getBrandName());
            orderInfoProductResponse.setAbnormal(infoVo.getAbnormal());
            orderInfoProductResponse.setExchangeRate(infoVo.getExchangeRate());
            //退款信息
            orderInfoProductResponse.setRefundReasonTime(infoVo.getRefundReasonTime());
            List<StoreOrderStatus> storeOrderStatusList = storeOrderStatusService.list(Wrappers.lambdaQuery(StoreOrderStatus.class).eq(StoreOrderStatus::getChangeType, Constants.ORDER_LOG_REFUND_PRICE)
                    .eq(StoreOrderStatus::getOrderNumber, infoVo.getChildOrderNumber()).notLike(StoreOrderStatus::getChangeMessage, "失败").orderByAsc(StoreOrderStatus::getCreateTime));
            if(CollectionUtils.isNotEmpty(storeOrderStatusList)){
                List<RefundInfo> refundInfoList = storeOrderStatusList.stream().map(e -> new RefundInfo().setRefundPrice(new BigDecimal(e.getChangeMessage().substring(e.getChangeMessage().indexOf("用户") + 2, e.getChangeMessage().indexOf("元"))))
                        .setRefundTime(e.getCreateTime()).setRefundType(e.getChangeMessage().contains("退货退款") ? 2 : 1)).collect(Collectors.toList());
                orderInfoProductResponse.setRefundInfoList(refundInfoList);
            }
            //加价计算方式
            String calculation = priceUtil.getCalculation(productInfo.getMarkupType(), productInfo.getPriceChange(),null);
            int count = storeOrderStatusService.count(Wrappers.lambdaQuery(StoreOrderStatus.class).eq(StoreOrderStatus::getChangeType, Constants.ORDER_UPDATE_PRICE).eq(StoreOrderStatus::getOid, id)
                    .eq(StoreOrderStatus::getOrderNumber, infoVo.getChildOrderNumber()));
            if(count > 0){
                calculation = "订单提交后修改价格";
            }
            orderInfoProductResponse.setCalculation(calculation);
            orderInfoProductResponse.setCouponPrice(infoVo.getCouponPrice());
            productList.add(orderInfoProductResponse);
        }
        storeOrderInfoResponse.setProductList(productList);
        return storeOrderInfoResponse;
    }

    private List<StoreOrderExcelVo> formatStoreOrderExcelVoNew(List<StoreOrderInfo> childOrderList) {
        List<StoreOrderExcelVo> storeOrderExcelVoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(childOrderList)) {
            return storeOrderExcelVoList;
        }
        //主订单集合
        List<Integer> orderIdList = childOrderList.stream().map(StoreOrderInfo::getOrderId).distinct().collect(Collectors.toList());
        List<StoreOrder> storeOrderList = dao.selectList(Wrappers.lambdaQuery(StoreOrder.class).in(StoreOrder::getId, orderIdList));
        Map<Integer, StoreOrder> storeOrderMap = storeOrderList.stream().collect(Collectors.toMap(StoreOrder::getId, e -> e));
        //下单用户列表
        Set<Integer> userIdList = storeOrderList.stream().map(StoreOrder::getUid).collect(Collectors.toSet());
        List<User> userList = userService.list(Wrappers.lambdaQuery(User.class).in(User::getUid, userIdList));
        //推广人列表
        Map<Integer, User> spreadMap = new HashMap<>();
        userList.forEach(e -> {
            if (spreadMap.get(e.getUid()) == null) {
                User spread = Optional.ofNullable(userService.getById(e.getSpreadUid())).orElse(new User());
                spreadMap.put(e.getUid(), spread);
            }
        });
        //商户信息
        List<ChannelMerchant> channelMerchants = channelMerchantService.list();
        Map<Integer, ChannelMerchant> channelMerchantMap = channelMerchants.stream().collect(Collectors.toMap(ChannelMerchant::getId, s -> s, (value1, value2) -> value1));
        //供应商信息
        Set<Integer> supplierIdList = childOrderList.stream().filter(e -> e.getSuppliersId() != null).map(StoreOrderInfo::getSuppliersId).collect(Collectors.toSet());
        Set<Integer> actualSupplierIdList = childOrderList.stream().map(StoreOrderInfo::getActualSupplierId).collect(Collectors.toSet());
        supplierIdList.addAll(actualSupplierIdList);
        List<Supplier> supplierList = supplierService.list(Wrappers.lambdaQuery(Supplier.class).in(Supplier::getId, supplierIdList));
        Map<Integer, String> supplierMap = supplierList.stream().collect(Collectors.toMap(Supplier::getId, Supplier::getSuppliersName));
        for (StoreOrderInfo storeOrderInfo : childOrderList) {
            StoreOrderExcelVo storeOrderExcelVo = new StoreOrderExcelVo();
            StoreOrder storeOrder = storeOrderMap.get(storeOrderInfo.getOrderId());
            storeOrderExcelVo.setCreateTime(DateFormatUtils.format(storeOrder.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            storeOrderExcelVo.setOrderNumber(storeOrder.getOrderId());
            //商户名
            if (null != storeOrder.getMerId()) {
                ChannelMerchant channelMerchant = channelMerchantMap.get(storeOrder.getMerId());
                if (null != channelMerchant) {
                    storeOrderExcelVo.setMerName(channelMerchant.getChannelName());
                }
            }
            //主订单
            storeOrderExcelVo.setOrderType(storeOrder.getShippingType() == 1 ? "快递订单" : "自提订单");
            storeOrderExcelVo.setCreateName(storeOrder.getCreateName());
            storeOrderExcelVo.setSpreadName(spreadMap.get(storeOrder.getUid()) != null ? spreadMap.get(storeOrder.getUid()).getNickname() : "");
            storeOrderExcelVo.setPayTypeStr(getPayType(storeOrder.getPayType()));
            if (storeOrder.getUseIntegral() > 0) {
                storeOrderExcelVo.setPayTypeStr(storeOrderExcelVo.getPayTypeStr() + " / 积分抵扣");
            }
            storeOrderExcelVo.setTotalPriceCNY(storeOrder.getPayPrice().add(storeOrder.getDeductionPrice()).add(storeOrder.getCouponPrice()));
            storeOrderExcelVo.setGoodsPriceCNY(storeOrder.getTotalPrice());
            storeOrderExcelVo.setFreightAndTaxPrice(storeOrder.getPayPostage());
            storeOrderExcelVo.setPayPrice(storeOrder.getPayPrice());
            storeOrderExcelVo.setDeductedPrice(storeOrder.getDeductionPrice());
            storeOrderExcelVo.setCouponPrice(storeOrder.getCouponPrice());
            storeOrderExcelVo.setChildOrderNumber(storeOrderInfo.getChildOrderNumber());
            storeOrderExcelVo.setOrderStatus(getStatusStr(storeOrderInfo.getStatus()));
            storeOrderExcelVo.setRefundStatus(getRefundStatusStr(storeOrderInfo.getRefundStatus()));
            //退款信息
            if (storeOrderInfo.getRefundStatus() == 2 || storeOrderInfo.getRefundStatus() == 3) {
                List<StoreAccountInfo> accountInfoList = storeAccountInfoService.list(Wrappers.lambdaQuery(StoreAccountInfo.class).eq(StoreAccountInfo::getUid, storeOrder.getUid())
                        .eq(StoreAccountInfo::getOrderId, storeOrderInfo.getChildOrderNumber()).eq(StoreAccountInfo::getTradeType, OrderTradeTypeEnum.REFUND.getType()).orderByAsc(StoreAccountInfo::getCreateTime));
                storeOrderExcelVo.setRefundPrice(accountInfoList.stream().map(StoreAccountInfo::getTradePrice).map(BigDecimal::toString).collect(Collectors.joining(" / ")));
                storeOrderExcelVo.setRefundTime(accountInfoList.stream().map(StoreAccountInfo::getCreateTime).map(e -> DateFormatUtils.format(e, "yyyy-MM-dd HH:mm:ss")).collect(Collectors.joining(" / ")));
                Set<Integer> adminIdList = accountInfoList.stream().map(StoreAccountInfo::getOperateId).collect(Collectors.toSet());
                if (CollectionUtils.isNotEmpty(adminIdList)) {
                    List<SystemAdmin> systemAdminList = systemAdminService.list(Wrappers.lambdaQuery(SystemAdmin.class).in(SystemAdmin::getId, adminIdList));
                    Map<Integer, String> systemAdminMap = systemAdminList.stream().collect(Collectors.toMap(SystemAdmin::getId, SystemAdmin::getRealName));
                    storeOrderExcelVo.setRefundOperator(accountInfoList.stream().map(StoreAccountInfo::getOperateId).map(systemAdminMap::get).collect(Collectors.joining(" / ")));
                }
            }
            StoreCartResponse storeCartResponse = JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class);
            StoreProductCartProductInfoResponse productInfo = storeCartResponse.getProductInfo();
            StoreProductAttrValue attrInfo = productInfo.getAttrInfo();
            //商品信息
            storeOrderExcelVo.setProductId(storeCartResponse.getProductId());
            storeOrderExcelVo.setProductName(productInfo.getStoreName());
            storeOrderExcelVo.setBrandName(productInfo.getBrandName());
            // 图片压缩
            String imgUrl = attrInfo.getImage();
            imgUrl = StringUtil.isEmpty(imgUrl) ? "" : imgUrl.substring(0, !imgUrl.contains("?") ? imgUrl.length() : imgUrl.indexOf("?")) + "?x-oss-process=image/resize,m_fill,w_100,h_100";
            storeOrderExcelVo.setImage(imgUrl);
            storeOrderExcelVo.setKeyword(productInfo.getKeyword());
            storeOrderExcelVo.setSpecification(attrInfo.getAttrValue());
            storeOrderExcelVo.setQuantity(storeCartResponse.getCartNum());
            //子订单价格信息
            storeOrderExcelVo.setOtPriceEUR(attrInfo.getOtPrice() == null ? productInfo.getOtPrice() : attrInfo.getOtPrice());
            storeOrderExcelVo.setSourceCostCNY(attrInfo.getSourceCost());
            storeOrderExcelVo.setCostCNY(attrInfo.getCost());
            //价格转换处理
            storeOrderExcelVo.setOtPriceCNY(priceUtil.eur2RmbStatic(storeOrderExcelVo.getOtPriceEUR(), storeOrderInfo.getExchangeRate()));
            storeOrderExcelVo.setSourceCostEUR(attrInfo.getSourceCost() == null ? null : priceUtil.rmb2EurStatic(attrInfo.getSourceCost(), storeOrderInfo.getExchangeRate()));
            storeOrderExcelVo.setCostEUR(attrInfo.getCost() == null ? null : priceUtil.rmb2EurStatic(attrInfo.getCost(), storeOrderInfo.getExchangeRate()));
            storeOrderExcelVo.setActualCostCNY(storeOrderInfo.getActualCost());
            storeOrderExcelVo.setPrice(attrInfo.getPrice());
            storeOrderExcelVo.setFirstPrice(attrInfo.getFirstPrice());
            storeOrderExcelVo.setSecondPrice(attrInfo.getSecondPrice());
            storeOrderExcelVo.setTaxPrice(attrInfo.getTaxPrice());
            storeOrderExcelVo.setProductPaidPrice(attrInfo.getProductPaidPrice());
            storeOrderExcelVo.setSubDeductionPrice(storeOrderInfo.getDeductionPrice());
            storeOrderExcelVo.setSubCouponPrice(storeOrderInfo.getCouponPrice());
            storeOrderExcelVo.setPaidPrice(storeOrderInfo.getPayPrice());
            if (storeOrderInfo.getActualSupplierId() != null && storeOrderInfo.getActualCost() != null) {
                storeOrderExcelVo.setActualSupplierName(supplierMap.get(storeOrderInfo.getActualSupplierId()));
                storeOrderExcelVo.setActualCostEur(storeOrderInfo.getActualCostEur());
            }
            if (Objects.nonNull(storeOrderInfo.getActualStockAreaCode())) {
                storeOrderExcelVo.setActualStockAreaName(StockAreaTempEnum.valueOf(storeOrderInfo.getActualStockAreaCode()).getStockAreaName());
            }
            if (storeOrderInfo.getSuppliersId() != null) {
                storeOrderExcelVo.setSupplierName(supplierMap.get(storeOrderInfo.getSuppliersId()));
            }
            //发货信息
            storeOrderExcelVo.setTempName(StockAreaTempEnum.getByTempId(productInfo.getTempId()).getStockAreaName());
            if (OrderStatusEnum.SHIPPED.getCode().equals(storeOrderInfo.getStatus()) || OrderStatusEnum.COMPLETE.getCode().equals(storeOrderInfo.getStatus())) {
                List<OrderInfoDelivery> orderInfoDeliveryList = orderInfoDeliveryService.list(Wrappers.lambdaQuery(OrderInfoDelivery.class).eq(OrderInfoDelivery::getOrderInfoId, storeOrderInfo.getId()).orderByAsc(OrderInfoDelivery::getId));
                storeOrderExcelVo.setDeliveryTime(orderInfoDeliveryList.stream().map(OrderInfoDelivery::getCreateTime).map(e -> DateFormatUtils.format(e, "yyyy-MM-dd HH:mm:ss")).collect(Collectors.joining(" / ")));
                storeOrderExcelVo.setDeliveryCompany(orderInfoDeliveryList.stream().map(OrderInfoDelivery::getDeliveryCompany).collect(Collectors.joining(" / ")));
                storeOrderExcelVo.setDeliveryNumber(orderInfoDeliveryList.stream().map(OrderInfoDelivery::getDeliveryNumber).collect(Collectors.joining(" / ")));
            }
            //收货人信息
            storeOrderExcelVo.setRealName(storeOrder.getRealName());
            storeOrderExcelVo.setUserPhone(storeOrder.getUserPhone());
            storeOrderExcelVo.setDetail(storeOrder.getUserAddress());
            storeOrderExcelVo.setIdCard(storeOrder.getIdCard());

            //商品采购信息
            if(Objects.equals(storeOrderInfo.getIsEurope(),ProductTypeEnum.INSIDE.getCode())){
                storeOrderExcelVo.setProcureStatus(ProcureStatusEnum.NO_PROCURE.getTypeName());
            } else if(Objects.equals(storeOrderInfo.getAutonomous(),1)){
                storeOrderExcelVo.setProcureStatus(ProcureStatusEnum.AUTO_PROCURE.getTypeName());
            } else {
                if(BooleanUtils.isTrue(storeOrderInfo.getIsVirtual())){
                    storeOrderExcelVo.setProcureStatus( ProcureStatusEnum.FOR_PROCURE.getTypeName());
                }else{
                    PurchaseGoods automaticPurchaseGoods =  purchaseGoodsService.getOne(Wrappers.lambdaQuery(PurchaseGoods.class).eq(PurchaseGoods::getPushType, 0).eq(PurchaseGoods::getStoreOrderInfoId, storeOrderInfo.getId()).eq(PurchaseGoods::getPushStatus, 1)
                            .orderByDesc(PurchaseGoods::getCreateTime).last("LIMIT 1"));
                    if (automaticPurchaseGoods != null) {
                        storeOrderExcelVo.setProcureStatus(ProcureStatusEnum.PROCURE.getTypeName());
                        storeOrderExcelVo.setDeliveryOrderNo(automaticPurchaseGoods.getChannelOrderSn());
                    }
                    if (null == storeOrderExcelVo.getProcureStatus()) {
                        storeOrderExcelVo.setProcureStatus(ProcureStatusEnum.FOR_PROCURE.getTypeName());
                    }
                    PurchaseGoods purchaseGoods = Optional.ofNullable(purchaseGoodsService.getOne(Wrappers.lambdaQuery(PurchaseGoods.class).eq(PurchaseGoods::getStoreOrderInfoId, storeOrderInfo.getId()).eq(PurchaseGoods::getPushType, 1).eq(PurchaseGoods::getPushStatus, 1)
                            .orderByDesc(PurchaseGoods::getCreateTime).last("LIMIT 1"))).orElse(new PurchaseGoods());
                    storeOrderExcelVo.setManualDeliveryOrderNo(purchaseGoods.getChannelOrderSn());
                }
            }
            storeOrderExcelVo.setExchangeRate(storeOrderInfo.getExchangeRate());
            storeOrderExcelVoList.add(storeOrderExcelVo);
        }
        return storeOrderExcelVoList;
    }
}

